window.onload = function () {
    let cartTable = document.getElementById("cartTable");
    let tr = cartTable.children[1].rows;

    function getsubtotal(tr) {
        let price = tr.cells[2];
        let countInput = tr.getElementsByTagName("input")[1].value;
        let subtotal = parseFloat(price.innerHTML) * parseInt(countInput);
        tr.cells[4].innerHTML = subtotal;
        let reduce = tr.getElementsByClassName("reduce");
        if (countInput.value == 1) {
            reduce.innerHTML = "";
        } else {
            reduce.innerHTML = '-';
        }
        return subtotal;
    }

    let allTotal = 0;

    function getTotal(check_value, value) {
        if (check_value === "ON") allTotal += value;
        else allTotal -= value;
        document.getElementsByClassName("total-pull")[0].innerHTML = '￥' + allTotal.toFixed(1);
    }

    for (let i = 0; i < tr.length; i++) {
        tr[i].onclick = function (e) {
            let countInput = this.getElementsByTagName("input")[1];
            let value = parseInt(countInput.value);
            let cls = e.target.className;
            switch (cls) {
                case 'add':
                    countInput.value = value + 1;
                    getsubtotal(tr[i]);
                    break;
                case'reduce':
                    if (value > 1) {
                        countInput.value = value - 1;
                        getsubtotal(tr[i]);
                    }
                    break;
                case 'delete':
                    let conf = confirm("确定删除此商品吗？");

                    if (conf) {
                        this.parentNode.removeChild(this);
                    }
                    break;
                case 'check':
                    let check = tr[i].getElementsByClassName("check")[0];
                    check.value = check.value === "ON" ? "OFF" : "ON";
                    getTotal(check.value, getsubtotal(tr[i]));
                    break;
            }
        }
    }
}